// pages/detailExpress/index.js
const app = getApp();
import {
	dateFormat,
	ToComment,
	needLogin
} from "../../Utils/Utils"

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		CustomBar: app.globalData.CustomBar, // 头部整体高度
		StatusBar: app.globalData.StatusBar, // 状态栏高度
		windowHeight: app.globalData.windowHeight, // 屏幕整体高度
		scrollHeight: 0, // scroll高度
		onFocus: false, // 自动聚焦，拉起键盘
		count: 0, // 当前输入的字数
		textAreaValue: '', // 用户输入的评论
		show: false, // 画廊开关
		index: 0, // 画廊下标
		comments: [],
		limit: 5,
		data: {
			isPraise: false,
			comment: 0,
			acticleId: "",
			image: "",
			userName: "",
			college: "",
			news: "",
			pictures: [],
			time: "",
		}
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		let that = this
		that.setData({
			scrollHeight: that.data.windowHeight - that.data.CustomBar - 42,
		})
		const event = this.getOpenerEventChannel()
		if (!!event.on) {
			event.on('getData', function (data) {
				that.setData({
					...data
				})
				that.getCommentsInfo(data.data.acticleId)
			})
		}
		if (options._id) {
			// 通过options进入此页面
			// 根据文章的id加载页面
			// 加载文章信息
			that.getArticleInfoById(options._id)
			// 加载文章评论
			that.getCommentsInfo(options._id)
		}
	},
	/**
	 * 获取文章信息
	 * @param {}} id 
	 */
	getArticleInfoById(id) {
		let that = this;
		wx.cloud.callFunction({
			name: "operation",
			data: {
				function: "getActicleByid",
				_id: id,
			}
		}).then(res => {
			let info = res.result.list[0]
			let user = info.user[0]
			that.setData({
				data: {
					acticleId: info._id,
					image: user.avatarUrl, // 用户头像
					userName: user.nickName, // 用户名
					colleges: user.colleges, // 用户学院
					pictures: info.pictures, // 图片
					time: dateFormat("YYYY-mm-dd HH:MM", new Date(info.timestamp)),
					comment: 0,
					isOver: info.isOver,
					news: info.text,
					id: info._id,
				}
			})
		}).catch(err => {
			console.log(err)
		})
		// 获取评论数量
		wx.cloud.callFunction({
				name: "operation",
				data: {
					function: "getCommentsNum",
					_id: id
				}
			}).then(res => {
				if (res.result.list.length > 0) {
					let data = this.data.data
					data.comment = res.result.list[0].count
					that.setData({
						data: data
					})
				}
			})
			.catch(err => {
				console.log(err)
			})
		// 获取是否点赞过此文章
		wx.cloud.callFunction({
				name: "operation",
				data: {
					function: "isPraised",
					articleId: id
				}
			}).then(res => {
				that.setData({
					isPraise: res.result.total > 0
				})
			})
			.catch(err => {
				console.log(err)
			})
	},
	/**
	 * 获取文章评论信息
	 * @param {id} param 
	 */
	getCommentsInfo: function (param) { // 获取评论信息 param为CustomExpress 组件里id
		let that = this
		let limit = that.data.limit
		let skip = that.data.comments.length
		if (skip % limit != 0) {
			return
		}
		wx.cloud.callFunction({
			name: "operation",
			data: {
				function: "getComments",
				_id: param,
				skip: skip,
				limit: limit
			}
		}).then(res => {
			let lists = res.result.list
			let comments = []
			for (let list of lists) {
				comments.push({
					id: list.user[0]._openid, // 用户id
					image: list.user[0].avatarUrl,
					userName: list.user[0].nickName,
					comment: list.comment,
					time: dateFormat("YYYY-mm-dd HH:MM", new Date(list.timestamp))
				})
			}
			that.setData({
				comments: that.data.comments.concat(comments)
			})
		}).catch(err => {
			console.log(err)
		})
	},

	/**
	 * 触底加载
	 */
	bindscrolltolower() {
		this.getCommentsInfo(this.data.data.acticleId)
	},

	openTextArea: function () {
		this.setData({
			onFocus: true
		})
	},

	editText: function (e) { // 获取表单域内容
		let maxlength = 50
		let temp = 0
		temp = e.detail.value.length > maxlength ? maxlength : e.detail.value.length
		let that = this
		that.setData({
			textAreaValue: e.detail.value,
			count: temp
		})
	},

	cancelComment: function () { // 取消评论
		let that = this
		that.setData({
			onFocus: false
		})
	},

	issue: function () { // 发送评论
		let that = this
		let textAreaValue = that.data.textAreaValue
		if (!textAreaValue) {
			return 0
		}
		needLogin(getCurrentPages().__route__, () => {
			ToComment(textAreaValue, that.data.data.acticleId, (e) => {
				if (e.errMsg.indexOf("ok") >= 0) {
					// 评论成功
					// 重新获取一下评论信息
					// 清空评论重新加载
					that.setData({
						comments: []
					})
					that.getCommentsInfo(this.data.data.acticleId)
				}
			})
		})
		//清空评论data
		that.setData({
			textAreaValue: ""
		})
	},


	goBack: function () { // 返回键
		let pages = getCurrentPages(); //当前页面
		let beforePage = pages[pages.length - 2]; //前一页
		wx.navigateBack({
			success: function () {
				beforePage.onLoad(); // 执行前一个页面的onLoad方法
			}
		});
	},

	goUserDetail(param) { // 跳转编辑交易地点页面
		let {
			id
		} = param.currentTarget.dataset
		wx.navigateTo({
			url: '../userDetail/index?openid=' + id,
		})
	},

	/**
	 * 点赞
	 * @param {*} e 
	 */
	praised() {
		let that = this;
		if (!(that.isPraise || that.data.isPraise)) {
			that.setData({
				isPraise: true
			})
			wx.cloud.callFunction({
					name: "operation",
					data: {
						function: "praise",
						articleId: that.data.data.acticleId
					}
				}).then(res => {
				})
				.catch(err => {
					console.log(err)
				})
		}
	},

	openPic: function (e) { // 打开画廊
		let {
			index
		} = e.currentTarget.dataset
		this.setData({
			index,
			show: true
		})
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})